package jiali.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean();
        //设置安全管理器
        filterFactory.setSecurityManager(securityManager);

        Map<String, String> filterMap = new LinkedHashMap<>();
        /*
        添加shiro的内置过滤器
            anno :无需认证即可访问
            authc :必须认证才可以访问
            user :必须拥有记住我 功能才可以用
            perm :拥有对某个资源的权限才能访问
            role :拥有某个角色权限才能访问
         */
        filterMap.put("/user/add", "authc");
        filterMap.put("/user/update", "anon");
        filterMap.put("/user/add", "perms[user]");
        filterFactory.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        filterFactory.setLoginUrl("/toLogin");
        filterFactory.setUnauthorizedUrl("/unauthorized");

        return filterFactory;
    }
    //DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("myRealm") UserRealmConfig realm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(realm);
        return manager;
    }


    //创建realm对象
    @Bean(name = "myRealm")
    public UserRealmConfig getUserRealmConfig() {
        return new UserRealmConfig();
    }
}
